package main

import (
	"encoding/json"
	"log"
	"net/http"
)

func userLogin(write http.ResponseWriter, r *http.Request) {
	// 获取参数
	r.ParseForm()
	mobile := r.PostForm.Get("mobile")
	password := r.PostForm.Get("password")

	loginOk := false
	if mobile == "15055108888" && password == "111111" {
		loginOk = true
	}

	// str := `{"code":0, "data":{"id":1, "token":"token"}}`
	if loginOk {
		// str = `{"code":-1, "msg":"密码不正确"}`
		data := make(map[string]interface{})
		data["id"] = 1
		data["token"] = "token"
		Resp(write, 0, data, "")
	} else {
		Resp(write, -1, nil, "密码不正确")
	}
	//io.WriteString(write, "hello")
}

type H struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

func Resp(write http.ResponseWriter, code int, data interface{}, msg string) {
	write.Header().Set("Content-Type", "application/json")
	write.WriteHeader(http.StatusOK)

	h := H{
		Code: code,
		Msg:  msg,
		Data: data,
	}
	ret, err := json.Marshal(h)
	if err != nil {
		log.Println(err.Error())
	}
	//write.Write([]byte(str))
	write.Write(ret)
}
func main() {

	// 绑定请求和处理函数
	http.HandleFunc("/user/login", userLogin)
	// 提供静态资源目录访问支持
	//http.Handle("/", http.FileServer(http.Dir(".")))
	// 指定目录静态文件支持
	http.Handle("/asset", http.FileServer(http.Dir(".")))
	// 启动web服务器
	http.ListenAndServe(":8888", nil)
}
